<template>
  <div class="home-page">
    <!-- 轮播图区域 -->
    <section class="hero-section">
      <div class="container">
        <Carousel 
          :items="carouselItems"
          height="500px"
          @button-click="handleCarouselButtonClick"
        />
      </div>
    </section>

    <!-- 特色分类 -->
    <section class="categories-section">
      <div class="container">
        <h2 class="section-title">热门分类</h2>
        <div class="categories-grid">
          <div 
            v-for="category in categories" 
            :key="category.id"
            class="category-item card-shadow"
            @click="goToCategory(category)"
          >
            <div class="category-icon">
              <img :src="category.image" :alt="category.name" />
            </div>
            <h3 class="category-name">{{ category.name }}</h3>
            <p class="category-count">{{ category.count }} 种商品</p>
          </div>
        </div>
      </div>
    </section>

    <!-- 热门商品 -->
    <section class="featured-products">
      <div class="container">
        <div class="section-header">
          <h2 class="section-title">热门商品</h2>
          <el-button type="primary" @click="$router.push('/products')">
            查看更多
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        
        <div class="products-grid">
          <ProductCard 
            v-for="product in featuredProducts"
            :key="product.id"
            :product="product"
          />
        </div>
      </div>
    </section>

    <!-- 品牌展示 -->
    <section class="brands-section">
      <div class="container">
        <h2 class="section-title">合作品牌</h2>
        
        <!-- 加载状态 -->
        <div v-if="brandsLoading" class="brands-loading">
          <div class="loading-spinner"></div>
          <p>正在加载合作品牌...</p>
        </div>
        
        <!-- 错误状态 -->
        <div v-else-if="brandsError" class="brands-error">
          <p>⚠️ 加载失败: {{ brandsError }}</p>
          <el-button @click="fetchBrands" type="primary" size="small">
            重新加载
          </el-button>
        </div>
        
        <!-- 品牌展示 -->
        <div v-else class="brands-scroll">
          <div class="brands-track">
            <!-- 第一组品牌 -->
            <div 
              v-for="brand in brands"
              :key="'first-' + brand.id"
              class="brand-item"
            >
              <div class="brand-content">
                <h3 class="brand-name">{{ brand.name }}</h3>
                <p class="brand-description">{{ brand.description }}</p>
              </div>
            </div>
            <!-- 第二组品牌（用于无缝循环） -->
            <div 
              v-for="brand in brands"
              :key="'second-' + brand.id"
              class="brand-item"
            >
              <div class="brand-content">
                <h3 class="brand-name">{{ brand.name }}</h3>
                <p class="brand-description">{{ brand.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Carousel from '@/components/Carousel.vue'
import ProductCard from '@/components/ProductCard.vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { partnersAPI } from '@/utils/api'

export default {
  name: 'HomePage',
  components: {
    Carousel,
    ProductCard,
    ArrowRight
  },
  setup() {
    const router = useRouter()
    
    // 轮播图数据
    const carouselItems = ref([
      {
        id: 1,
        image: require('@/assets/images/AD0Ivf6DDBACGAAg_rLX_gUopKbK7QYwgA847gM.jpg'),
        title: '优质宠物用品',
        subtitle: '为您的爱宠提供最好的生活用品',
        buttonText: '立即购买',
        link: '/products'
      },
      {
        id: 2,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgh5nI_wUogJCK1gUwzgQ4sAM.png.webp'),
        title: '健康宠物食品',
        subtitle: '营养均衡，让宠物健康成长',
        buttonText: '了解更多',
        link: '/products?category=food'
      },
      {
        id: 3,
        image: require('@/assets/images/ABUIABAEGAAgsP7PxAYokJvNkwEwsAk4sAk.png'),
        title: '专业宠物护理',
        subtitle: '专业的宠物护理产品和服务',
        buttonText: '预约服务',
        link: '/products?category=care'
      }
    ])
    
    // 分类数据
    const categories = ref([
      {
        id: 1,
        name: '宠物食品',
        image: require('@/assets/images/AD0I9ruEDBAEGAAg_InB_wUo2qTC3AEwgAY4gAY_400x400.png'),
        count: 156,
        slug: 'food'
      },
      {
        id: 2,
        name: '玩具用品',
        image: require('@/assets/images/AD0I9ruEDBAEGAAg_p7B_wUoyPiemAYwgAY4gAY_400x400.png'),
        count: 89,
        slug: 'toys'
      },
      {
        id: 3,
        name: '护理用品',
        image: require('@/assets/images/AD0I9ruEDBAEGAAg2ITB_wUogLTVvAcwgAY4gAY_400x400.png'),
        count: 124,
        slug: 'care'
      },
      {
        id: 4,
        name: '服装配饰',
        image: require('@/assets/images/AD0I9ruEDBAEGAAg5vLF_wUouYyxITCABjiABg_400x400.png'),
        count: 67,
        slug: 'clothing'
      }
    ])
    
    // 热门商品数据
    const featuredProducts = ref([
      {
        id: 1,
        name: '高端猫粮 海洋鱼味',
        description: '精选深海鱼类，营养丰富，口感佳',
        price: 299,
        originalPrice: 399,
        image: require('@/assets/images/AD0I9ruEDBAEGAAg6Z-B_wUojMjq3QYwgAY4gAY_400x400.png'),
        category: 'food'
      },
      {
        id: 2,
        name: '智能宠物玩具球',
        description: '自动滚动，陪伴宠物玩耍',
        price: 129,
        image: 'https://manymart.com.hk/cdn/shop/files/image_22fcf830-c5cd-4e72-a78b-7a4b8bce5fee.jpg?v=1712771610&width=713',
        category: 'toys'
      },
      {
        id: 3,
        name: '宠物洗护套装',
        description: '温和无刺激，深层清洁护理',
        price: 89,
        originalPrice: 120,
        image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwj3Kark-4F1AqjhuUIIWg7islNDNfzBj8Ag&s',
        category: 'care'
      },
      {
        id: 4,
        name: '可爱宠物服装',
        description: '时尚舒适，四季可穿',
        price: 68,
        image: 'https://gw.alicdn.com/imgextra/i1/11991366/O1CN01RUYJpU1LxfXACzbFq_!!11991366.jpg_Q75.jpg_.webp',
        category: 'clothing'
      },
      {
        id: 5,
        name: '营养宠物零食',
        description: '天然健康，训练奖励必备',
        price: 45,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgsZ-B_wUom8Kd-wQwgAY4gAY_400x400.png'),
        category: 'food'
      },
      {
        id: 6,
        name: '舒适宠物窝',
        description: '柔软舒适，给宠物温暖的家',
        price: 188,
        image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQUMWSmj5v8v0i19_d61a-Vkf59wpIOLdzLaw&s',
        category: 'accessories'
      }
    ])
    
    // 品牌数据和加载状态
    const brands = ref([])
    const brandsLoading = ref(false)
    const brandsError = ref(null)
    
    // 获取品牌数据
    const fetchBrands = async () => {
      try {
        brandsLoading.value = true
        brandsError.value = null
        
        const response = await partnersAPI.getAll({ status: 'active' })
        
        if (response.success) {
          brands.value = response.data
          console.log('✅ 合作品牌数据加载成功:', response.data.length, '个品牌')
        } else {
          throw new Error(response.message || '获取品牌数据失败')
        }
      } catch (error) {
        console.error('❌ 获取品牌数据失败:', error)
        brandsError.value = error.message
        
        // 失败时使用备用数据
        brands.value = [
          { id: 1, name: '皇家宠物食品', description: '全球营养专家' },
          { id: 2, name: '雀巢普瑞纳', description: '宠物营养领导者' },
          { id: 3, name: '玛氏宠物护理', description: '国际护理品牌' }
        ]
      } finally {
        brandsLoading.value = false
      }
    }
    
    const handleCarouselButtonClick = (item) => {
      if (item.link) {
        router.push(item.link)
      }
    }
    
    const goToCategory = (category) => {
      router.push(`/products?category=${category.slug}`)
    }
    
    onMounted(() => {
      console.log('首页加载完成')
      // 获取品牌数据
      fetchBrands()
    })
    
    return {
      carouselItems,
      categories,
      featuredProducts,
      brands,
      brandsLoading,
      brandsError,
      fetchBrands,
      handleCarouselButtonClick,
      goToCategory,
      // Element Plus icons
      ArrowRight
    }
  }
}
</script>

<style scoped>
.home-page {
  min-height: 100vh;
}

/* 轮播图区域 */
.hero-section {
  margin-bottom: 60px;
}

/* 通用样式 */
.section-title {
  font-size: 2rem;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 3rem;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #FF8C00, #FFB300);
  border-radius: 2px;
}

/* 分类区域 */
.categories-section {
  padding: 60px 0;
  background: white;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 30px;
  margin-top: 2rem;
}

.category-item {
  text-align: center;
  padding: 40px 20px;
  background: white;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.category-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  border-radius: 50%;
  overflow: hidden;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.category-icon img {
  width: 60px;
  height: 60px;
  object-fit: cover;
}

.category-name {
  font-size: 1.3rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.category-count {
  color: #666;
  font-size: 0.9rem;
}

/* 热门商品区域 */
.featured-products {
  padding: 80px 0;
  background: #f8f9fa;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3rem;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 30px;
}

/* 品牌区域 */
.brands-section {
  padding: 60px 0;
  background: white;
  overflow: hidden;
}

.brands-scroll {
  overflow: hidden;
  mask: linear-gradient(90deg, transparent, white 20%, white 80%, transparent);
}

.brands-track {
  display: flex;
  animation: scroll 20s linear infinite;
  gap: 60px;
}

.brand-item {
  flex-shrink: 0;
  width: 200px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;
}

.brand-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(255, 140, 0, 0.15);
  border-color: #FF8C00;
  background: #fff8f0;
}

.brand-content {
  text-align: center;
  padding: 10px;
}

.brand-name {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
  transition: color 0.3s ease;
}

.brand-item:hover .brand-name {
  color: #FF8C00;
}

.brand-description {
  font-size: 0.8rem;
  color: #666;
  margin: 0;
  line-height: 1.2;
  transition: color 0.3s ease;
}

.brand-item:hover .brand-description {
  color: #555;
}

@keyframes scroll {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-50%);
  }
}

/* 品牌加载状态 */
.brands-loading {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #FF8C00;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.brands-loading p {
  margin: 0;
  font-size: 1rem;
}

/* 品牌错误状态 */
.brands-error {
  text-align: center;
  padding: 60px 20px;
  color: #ff4757;
}

.brands-error p {
  margin: 0 0 20px 0;
  font-size: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .section-title {
    font-size: 1.6rem;
    margin-bottom: 2rem;
  }
  
  .categories-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
  }
  
  .category-item {
    padding: 30px 15px;
  }
  
  .category-icon {
    width: 60px;
    height: 60px;
  }
  
  .category-icon img {
    width: 40px;
    height: 40px;
  }
  
  .products-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .featured-products,
  .categories-section {
    padding: 40px 0;
  }
}

@media (max-width: 480px) {
  .categories-grid {
    grid-template-columns: 1fr;
  }
  
  .hero-section {
    margin-bottom: 40px;
  }
}
</style>
